package com.student.education.service.impl;

import com.student.education.entity.Term;
import com.student.education.dao.TermDao;
import com.student.education.service.TermService;
import com.student.education.to.TermTo;
import com.student.education.vo.TermVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 学期班级表(Term)表服务实现类
 *
 * @author makejava
 * @since 2021-10-08 22:59:54
 */
@Service("termService")
public class TermServiceImpl implements TermService {
    @Resource
    private TermDao termDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Term queryById(Integer id) {
        return this.termDao.queryById(id);
    }


    /**
     * 新增数据
     *
     * @param term 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(TermVo term) {
        term.setClassIds(StringUtils.join(term.getClassId().toArray(), ","));
        return this.termDao.insert(term);
    }

    /**
     * 修改数据
     *
     * @param term 实例对象
     * @return 实例对象
     */
    @Override
    public int update(TermVo term) {
        String classIds = StringUtils.join(term.getClassId().toArray(), ",");
        term.setClassIds(classIds);
        return this.termDao.update(term);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.termDao.deleteById(id) > 0;
    }

    @Override
    public List<TermTo> queryAll(String termName) {
        List<TermTo> termTos = termDao.queryAll(termName);
        for (int i =0;i<termTos.size();i++){
            termTos.get(i).setClassId(Arrays.asList(termTos.get(i).getClassIds().split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList()));
        }
        return termTos;
    }
}
